package main

import (
	"database/sql"
	"errors"
	"fmt"
	_ "github.com/denisenkom/go-mssqldb"
	_ "github.com/go-sql-driver/mysql"
	"log"
	"time"
)

/**
写入数据到mysql
*/
func writeGdArea(connString string, ch chan string) {

	conn, err := sql.Open("mysql", connString)

	if err != nil {
		log.Fatal("Open Connection failed:", err.Error())
	}

	defer conn.Close() //随手关闭数据库是个好习惯

	i := 1

	for sql := range ch {
		fmt.Printf("execute sql: :%d\n", i)
		//ret, err :=conn.Exec(sql)
		conn.Exec(sql)
		//if err != nil {
		//	fmt.Printf("update failed, err:%v\n", err)
		//	return
		//}
		//n, err := ret.RowsAffected() //操作影响的行数
		//if err != nil {
		//	fmt.Printf("get RowsAffected failed, err:%v\n", err)
		//	return
		//}
		//
		//fmt.Print(n)

		i++
	}

	//wg.Done()

}

func push(q chan string, sql string) error {
	select {
	case q <- sql:
		return nil
	default:
		return errors.New("queue full")
	}

}

func get(q chan string) (string, error) {
	var sql string
	select {
	case sql = <-q:
		return sql, nil
	default:
		return "", errors.New("queue empty")
	}

}

func readGdArea(connString string, c chan string) {

	log.Println("start read gd_area ")

	///建立连接
	conn, err := sql.Open("mssql", connString)
	if err != nil {
		log.Fatal("Open Connection failed:", err.Error())
	}
	defer conn.Close()

	//产生查询语句的Statement
	stmt, err := conn.Prepare(`select  [ConID]
      ,[OrgID]
      ,[ConName]
      ,[NewConID]
      ,[hs]
      ,[area]
      ,[jfhs]
      ,[jfarea]
      ,ISNULL([ManagerName], '') from [240].[ZS_YHRLS].dbo.GD_AREA`)
	if err != nil {
		log.Fatal("Prepare failed:", err.Error())
	}
	defer stmt.Close()

	rows, err := stmt.Query()
	if err != nil {
		log.Fatal("Query failed:", err.Error())
	}

	for rows.Next() {
		var ConID string
		var OrgID string
		var ConName string
		var NewConID string
		//var BWJB sql.NullString
		var hs = "0"
		var area = "0"
		var jfhs = "0"
		var jfarea = "0"
		var ManagerName = ""
		rows.Scan(&ConID, &OrgID, &ConName, &NewConID, &hs, &area, &jfhs, &jfarea, &ManagerName)
		sql := fmt.Sprintf("insert into hes_con_payment(conid, totalhouses, totalarea, payhouses, payarea, managername) values('%s', %s, %s, %s, %s, '%s') "+
			"ON DUPLICATE KEY UPDATE totalhouses=%s, totalarea=%s, payhouses=%s, payarea=%s, managername='%s';",
			NewConID,
			hs,
			area,
			jfhs,
			jfarea,
			ManagerName,
			hs,
			area,
			jfhs,
			jfarea,
			ManagerName,
		)
		//fmt.Println(sql)
		for len(c) >= ChacheLen {
			time.Sleep(1)
		}

		push(c, sql)
	}
	defer rows.Close()

	//wg.Done()
}

type SqlConn struct {
	server   string
	port     int
	user     string
	password string
	database string
}
